<?php
// 批量导入处罚规则
namespace Beerus\Modules\IdealHome\Actions;

use Doraemon\model\Designer as mDesigner;
use Doraemon\model\Member as mMember;
use Doraemon\model\DecoCompany as mDecoCompany;
use Doraemon\model\Photos;
use Doraemon\pockets\constInterface\Designer\IdealHomeTab as iIdealHomeTab;
use Doraemon\pockets\excel\ReadExcel;
use Encore\Admin\Actions\Action;
use Encore\Admin\Admin;
use Illuminate\Http\Request;
use Doraemon\model\IdealHomeTab\IdealHomeVideo as mIdealHomeVideo;

class ImportVideo extends Action implements iIdealHomeTab {
    public $name = '批量导入';

    protected $selector = '.import-post';

    public function handle(Request $request) {
        $oFile = $request->file('file');
        $newFile = 'ideal_home_video.xls';
        $newFilePath = '/tmp/'.$newFile;
        $rs = move_uploaded_file($oFile, $newFilePath);
        if (!$rs) {
            return $this->response()->error("上传错误");
        }
        $oExcel = new ReadExcel($newFile);
        try {
            $aExcelRawData = $oExcel->getExcelDataNoHeader($newFilePath);
        } catch (\PHPExcel_Reader_Exception $exception) {
            return $this->response()->error("上传错误");
        }
        try {
            mIdealHomeVideo::action(function () use ($aExcelRawData) {
                $aAddData = [];
                $iVideoLength = count($aExcelRawData);
                if ($iVideoLength < 1) {
                    throw new \Exception("请确认表格格式～");
                }
                for ($i = 1; $i < $iVideoLength; $i ++) {
                    $iNoteId = trim($aExcelRawData[$i][0]);
                    if (empty($iNoteId)) {
                        continue;
                    }
                    $aNoteInfo = Photos::getPhotoById($iNoteId);
                    if (!$aNoteInfo || $aNoteInfo['status'] != Photos::STATUS_NORMAL) {
                        throw new \Exception("存在非视频note：{$iNoteId}");
                    }
                    $iMainAreaCode = $iOtherAreaCode = 0;
                    $aMemberInfo = mMember::getUserInfo($aNoteInfo['uid']);
                    if (mMember::AUTH_USER_DESIGNER == $aMemberInfo['type']) {
                        $aDesignerInfo = mDesigner::getInfo($aNoteInfo['uid']);
                        $iMainAreaCode = $aDesignerInfo['main_area_code'];
                        $iOtherAreaCode = $aDesignerInfo['other_area_code'];
                    } elseif (mMember::AUTH_DECO_COMPANY == $aMemberInfo['type']) {
                        $aDecoCompanyInfo = mDecoCompany::getByUid($aNoteInfo['uid']);
                        $iMainAreaCode = $aDecoCompanyInfo['main_area_code'];
                    }
                    $aAddData[] = [
                        'uid' => $aNoteInfo['uid'],
                        'admin_score' => $aNoteInfo['admin_score'],
                        'note_id' => $iNoteId,
                        'main_area_code' => $iMainAreaCode,
                        'other_area_code' => $iOtherAreaCode,
                        'admin_id' => \Encore\Admin\Facades\Admin::user()->id
                    ];
                }
                if (count($aAddData) > self::MAX_VIDEO_CNT) {
                    throw new \Exception("单次上传视频数量超过".self::MAX_VIDEO_CNT."个");
                }
                if (($iOldCnt = count(mIdealHomeVideo::getAllVideo())) && mIdealHomeVideo::delAllItem() !== $iOldCnt) {
                    throw new \Exception("删除历史note失败");
                }
                if (!($iAddCnt = mIdealHomeVideo::batchAddData($aAddData)) || $iAddCnt != count($aAddData)) {
                    throw new \Exception("批量添加note失败");
                }
                return true;
            });
        } catch (\Exception $e) {
            return $this->response()->error($e->getMessage());
        }
        return $this->response()->success('更新完毕')->refresh();
    }

    public function form() {
        $this->file('file', '请选择文件');
    }

    public function html() {
        return <<<HTML
<i class="fa fa-plus"></i>
<a class="btn btn-sm btn-success import-post">批量导入</a>
HTML;

    }
}